package com.yy.QSManage.service.other.table;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.yy.QSManage.exception.ServiceException;
import com.yy.QSManage.model.entity.FaSysSettings;
import com.yy.QSManage.service.FaSysSettingsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class TableToolService {

    @Autowired
    private TableToolMapper tableToolMapper;
    @Autowired
    private FaSysSettingsService settingsService;
    final String TABLE_DEFAULT_FIELD = "TABLE_DEFAULT_FIELD";

    /**
     * 检查表结构是否正确
     * @param tableName
     * @return
     */
    public void tableCheck(String tableName) {
        // 查询表格字段
        List<TableField> tableFields = tableToolMapper.getTableFields(tableName);
        // 获取表格默认字段
        FaSysSettings setting = settingsService.getByParam(FaSysSettings::getKeyName, TABLE_DEFAULT_FIELD);
        JSONArray values = JSONUtil.parseArray(setting.getValue());
        for (Object value : values) {
            boolean ifExist = tableFields.stream().anyMatch(field -> field.getField().equals(value.toString()));
            if(!ifExist){
                throw new ServiceException("缺少必须字段 "+value);
            }
        }
    }
}
